package event

import (
	"errors"
	"fmt"
	"yunj/pkg/yunj/app/enum/admin/taskenum"
	"yunj/pkg/yunj/app/model"
	"yunj/pkg/yunj/app/service/admin/adminservice"
	"yunj/pkg/yunj/app/service/admin/taskservice"
	"yunj/pkg/yunj/core/builder"
	"yunj/pkg/yunj/core/event"
)

// 事件订阅
var Subscribes = map[string][]*event.Listener{
	// 后台任务创建
	"admin.task.create": {
		&event.Listener{
			Id:      "listener_1",
			IsAsync: true,
			Handler: func(data any) (err error) {
				task, ok := data.(model.AdminTask)
				if !ok {
					err = errors.New("无效任务数据")
					return
				}
				return taskservice.Create(&task)
			},
		},
	},
	// 后台任务处理
	"admin.task.handle": {
		&event.Listener{
			Id:      "listener_1",
			IsAsync: true,
			Handler: func(data any) (err error) {
				taskIds, ok := data.([]uint64)
				if !ok {
					err = errors.New("无效任务id数据")
					return
				}
				return taskservice.Handle(taskIds...)
			},
		},
	},
	// 后台任务创建并立即执行
	"admin.task.create.handle": {
		&event.Listener{
			Id:      "listener_1",
			IsAsync: true,
			Handler: func(data any) (err error) {
				task, ok := data.(model.AdminTask)
				if !ok {
					err = errors.New("无效任务数据")
					return
				}
				err = taskservice.CreateHandle(&task)
				return
			},
		},
	},
	// 表格构建器导出任务
	"table.builder.export.task": {
		&event.Listener{
			Id:      "listener_1",
			IsAsync: true,
			Handler: func(p any) (err error) {
				data, ok := p.(builder.TableExportTaskEventData)
				if !ok {
					err = errors.New("无效导出任务事件数据")
					return
				}
				// 任务准备
				taskPrepare := &model.AdminTask{
					Id:    data.TaskId,
					Type:  taskenum.TYPE_TABLE_BUILDER_EXPORT,
					Title: fmt.Sprintf("导出%s.%s", data.RequestParam.Export.Filename, data.RequestParam.Export.FileExt),
					Snap: &model.MapJson{
						"request_param": data.RequestParam,
					},
				}
				if loginMember := adminservice.GetLoginMember(data.Table.GetGinContext()); loginMember != nil && loginMember.Id > 0 {
					taskPrepare.MemberId = loginMember.Id
				}
				// 创建任务
				if err = taskservice.Create(taskPrepare); err != nil {
					return
				}
				// 执行任务
				// err = taskservice.Handle()
				return
			},
		},
	},
}
